package opensource.xml.jdom;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.output.XMLOutputter;
import org.jdom.xpath.XPath;

/**
 * @author Guoxuepin(guoxp@bingosoft.net) 2009-3-4 上午11:42:25 ChangeLog:
 *         ReadMe:JDOM 读取XML配置文件的例子
 */

// <?xml version="1.0" encoding="UTF-8"?>
// <selects>
// <select>
// <id>1</id>
// <name>10086</name>
// </select>
// </selects>
public class CreateXMLByJDOM {

	Element idElement = new Element("id");

	Element valueElement = new Element("name");

	Element selectsElement = new Element("select");

	Element rootElement = new Element("selects");

	Document doc = new Document(rootElement);

	private void createXML() {
		idElement.addContent("1");
		valueElement.addContent("10086");
		selectsElement.addContent(idElement);
		selectsElement.addContent(valueElement);
		rootElement.addContent(selectsElement);

		XMLOutputter out = new XMLOutputter();
		out.getFormat().setEncoding("UTF-8");// 设置编码格式
		try {
			out.output(doc, new FileOutputStream("createByJDOM.xml"));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	private void modifyXML() {
		// CDATA cdata=new CDATA("自助渠道");
		String cdata = "自助渠道";
		try {
			Element selectsNode = (Element) XPath.selectSingleNode(
					selectsElement, "//selects/select/name");
			selectsNode.removeContent();
			selectsNode.addContent(cdata);
		} catch (JDOMException e) {
			e.printStackTrace();
		}

		// 修改完成记得保存到文件中
		XMLOutputter out = new XMLOutputter();
		out.getFormat().setEncoding("UTF-8");// 设置编码格式
		try {
			out.output(doc, new FileOutputStream("createByJDOM.xml"));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	public static void main(String[] args) {
		CreateXMLByJDOM createXMLByJDOM = new CreateXMLByJDOM();
		createXMLByJDOM.createXML();
		createXMLByJDOM.modifyXML();
	}

}
